package com.eshore.textanalyzer.elk.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eshore.textanalyzer.elk.common.ESRestClient;
import com.eshore.textanalyzer.elk.common.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

/**
 * @author xyd
 * @date 2021/5/21
 * 编写索引操作接口
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/index")
public class IndexController {

    // 带密码配置的
    @Autowired
    private ESRestClient restClient;

    /**
     * 新建索引
     * @param str 动态模板 json字符串格式
     * @param indexName 新建的索引名称 不能有大写
     * @return
     */
    @PostMapping(value = "createIndex")
    public ResponseMessage createIndex(String str, String indexName) {
        if (indexName == null || indexName == "") {
            return ResponseMessage.createByError("定义索引名称不能为空");
        }
        // 校验字符串是否为json格式
        try {
            JSONObject.parseObject(str);
        }catch (Exception e) {
            e.printStackTrace();
            return ResponseMessage.createByError("定义的动态模板JSON格式错误");
        }
        // 获取client对象
        RestHighLevelClient client = restClient.getClient();
        // 创建一个 创建索引的请求 索引名不能为大写
        CreateIndexRequest request = new CreateIndexRequest(indexName.toLowerCase());
        // 添加settings参数
        request.settings(Settings.builder()
                .put("index.refresh_interval","5s")
                .put("index.max_result_window","200000000")
                .put("index.number_of_shards", 3) // 分片
                .put("index.number_of_replicas", 2) // 副本
        );
        // The mapping for this type, provided as a JSON string
        request.mapping(str, XContentType.JSON);
        // 设置创建索引的超时
        request.setTimeout(TimeValue.timeValueMinutes(1));
        // The number of active shard copies to wait for before the create index API returns a response, as an int
        request.waitForActiveShards(ActiveShardCount.from(2));
        // The number of active shard copies to wait for before the create index API returns a response, as an ActiveShardCount
        request.waitForActiveShards(ActiveShardCount.DEFAULT);

        // 同步执行 等待响应
        try {
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
            // 响应信息
            boolean acknowledged = response.isAcknowledged(); // 指示是否所有节点都已确认请求
            boolean shardsAcknowledged = response.isShardsAcknowledged(); // 指示是否在超时之前为索引中的每个分片启动了必要数量的分片副本
            log.info("新建索引返回值===" + "acknowledged==" + acknowledged + "shardsAcknowledged==" + shardsAcknowledged);
            return ResponseMessage.createBySuccess("索引创建成功");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseMessage.createByError("索引创建失败");
        }
        // 异步执行 使用异步需要使用 listener监听执行情况
//        CreateIndexResponse response = client.indices().createAsync(request, RequestOptions.DEFAULT);
        // 将mapping转为json格式
//        JSONObject jsonObject = JSON.parseObject(str);
//        System.out.println(jsonObject);
//        return ResponseMessage.createBySuccess();
    }
}
